<template>
  <div>
    <h2>电商后台管理系统登录</h2>
    <el-form
      :model="userinfo"
      :rules="rules"
      ref="rulesfrom"
      label-width="100px"
      class="demo-userinfo"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userinfo.username" type="text" icon="el-icon-user-solid
"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" icon="el-icon-view">
        <el-input v-model="userinfo.password" type="password"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="postLogin('rulesfrom')"
          >登录</el-button
        >
        <el-button @click="resetLogin('rulesfrom')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //双向数据绑定数据
      userinfo: {
        username: "admin",
        password: "123456",
      },
      //表单格式验证
      rules: {
        username: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          {
            min: 3,
            max: 12,
            message: "长度在 3 到 12 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    //登录
    postLogin() {
      //自定义表单的验证
      this.$refs.rulesfrom.validate((res) => {
        if (res) {
          // 发送ajax请求
          this.$axios.post("/login", this.userinfo).then((res) => {
            // console.log(res);
            //解构赋值
            var { data, meta } = res.data;
            //判断是否登陆成功
            if (meta.status == 400) {
              //错误弹窗
              this.$message({
                type: "error",
                message: meta.msg,
              });
            } else if (meta.status == 200) {
              //登录成功弹窗
              this.$message({
                type: "success",
                message: meta.msg,
              });
              //调用vuex存储的token
              this.$store.commit("userchange", data);
              //本地存储作为home页面用户登录的凭据
              // localStorage.setItem("userinfo", JSON.stringify(data));
              //成功之后完成跳转
              this.$router.push({ path: "/home" });
            } else {
              this.$message({
                type: "error",
                message: meta.msg,
              });
            }
          });
        } else {
          this.$message({
            type: "warning",
            message: "格式错误，请注意格式！",
          });
          return false;
        }
      });
    },
    //取消登录
    resetLogin() {
      this.$refs.rulesfrom.resetFields();
    },
  },
  mounted() {},
};
</script>

<style>
.el-form {
  width: 500px;
  margin: 0 auto;
}
</style>